const WebSocket = require('ws');
const url = require('url');
const jwt = require('jsonwebtoken');
const Project = require('../models/project.model');
const sshService = require('./ssh.service');

class WebSocketService {
  constructor() {
    this.clients = new Map();
    this.statusPolling = new Map(); // 存储状态轮询定时器
  }

  // 开始服务器状态轮询
  async startStatusPolling(projectId) {
    if (this.statusPolling.has(projectId)) {
      return;
    }

    try {
      const project = await Project.findById(projectId);
      if (!project || !project.deploymentConfig?.serverConfig) {
        return;
      }

      const interval = setInterval(async () => {
        try {
          const status = await sshService.getServerStatus(project.deploymentConfig.serverConfig);
          this.sendServerStatus(projectId, status);
        } catch (error) {
          console.error(`获取服务器状态失败 (${projectId}):`, error);
          // 如果连续失败多次，可以考虑停止轮询
        }
      }, 10000); // 每10秒更新一次

      this.statusPolling.set(projectId, interval);
    } catch (error) {
      console.error('启动状态轮询失败:', error);
    }
  }

  // 停止服务器状态轮询
  stopStatusPolling(projectId) {
    const interval = this.statusPolling.get(projectId);
    if (interval) {
      clearInterval(interval);
      this.statusPolling.delete(projectId);
    }
  }

  // 当客户端连接时启动轮询
  initialize(server) {
    this.wss = new WebSocket.Server({ server });

    this.wss.on('connection', async (ws, req) => {
      try {
        const token = url.parse(req.url, true).query.token;
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        
        const projectId = url.parse(req.url, true).query.projectId;
        
        if (!this.clients.has(projectId)) {
          this.clients.set(projectId, new Set());
          // 当第一个客户端连接时启动状态轮询
          this.startStatusPolling(projectId);
        }
        this.clients.get(projectId).add(ws);

        ws.send(JSON.stringify({
          type: 'connected',
          message: '已连接到部署日志服务'
        }));

        ws.on('close', () => {
          if (this.clients.has(projectId)) {
            this.clients.get(projectId).delete(ws);
            if (this.clients.get(projectId).size === 0) {
              this.clients.delete(projectId);
              // 当最后一个客户端断开时停止状态轮询
              this.stopStatusPolling(projectId);
            }
          }
        });

      } catch (error) {
        ws.close();
      }
    });
  }

  // 向特定项目的所有客户端广播消息
  broadcast(projectId, data) {
    if (this.clients.has(projectId)) {
      this.clients.get(projectId).forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
          client.send(JSON.stringify(data));
        }
      });
    }
  }

  // 发送部署日志
  sendDeployLog(projectId, log) {
    this.broadcast(projectId, {
      type: 'deployLog',
      data: log
    });
  }

  // 发送部署状态更新
  sendDeployStatus(projectId, status) {
    this.broadcast(projectId, {
      type: 'deployStatus',
      data: status
    });
  }

  // 发送服务器状态更新
  sendServerStatus(projectId, status) {
    this.broadcast(projectId, {
      type: 'serverStatus',
      data: status
    });
  }
}

module.exports = new WebSocketService(); 